import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
import { isDynamicPermission } from '@/setting.js';
import { intoRecurse } from '@u/common.js';
import asyncRouters from './asyncRouters';
import moduleRouters from './moduleRouters';

Vue.use(VueRouter);

let routes = [
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录',
      isFullTitle: true
    },
    component: () => import(/* webpackChunkName: "login" */ '@v/login'),
  },
  {
    path: '/404',
    name: 'FourToFour',
    meta: {
      title: '404 not found',
      isFullTitle: true
    },
    component: () => import(/* webpackChunkName: "error" */ '@v/error/404.vue'),
  },
];

if (!isDynamicPermission) {
  const userPermission = [], affixRouters = [], allRouters = asyncRouters.concat(moduleRouters);
  routes = [...routes];

  allRouters.map(item => {
    const module = {
      name: item.name,
      redirect: item.redirect || '',
      meta: {
        ...item.meta,
        type: 1,
        isShow: item.isShow || false,
      },
      isModule: !!item.component,
      children: [],
    };

    function addMenu(menuList, children, callback) {
      if (menuList.length) {
        const tag = children.find(c => c.name == menuList[0].name);
        if (!tag) {
          children.push({
            name: menuList[0].name,
            redirect: menuList[0].redirect || '',
            meta: {
              title: menuList[0].title,
              isShow: true,
              type: 2,
            },
            children: [],
          });
        }
        addMenu(menuList.slice(1), children.find(c => c.name == menuList[0].name).children, callback);
      } else {
        callback && callback(children);
      }
    }
    function addParents(item, list, tag) {
      if (tag.meta) {
        tag.meta.parents = tag.meta.parents || [];
      } else {
        tag.meta = {
          parents: [],
        };
      }
      handleBelong(item.belong, tag);

      if (item.parentName) {
        const parent = list.find(t => t.name == item.parentName);
        if (parent) {
          tag.meta.parents.push({
            name: parent.name,
            title: parent.meta && parent.meta.title,
            type: parent.meta && parent.meta.type,
            redirect: parent.meta && parent.meta.redirect,
          });
          addParents(parent, list, tag);
          handleBelong(parent.belong, tag);
        }
      }
    }
    function handleBelong(belong, tag) {
      if (belong && belong.length) {
        const belongList = [];
        belong.map(b => {
          belongList.push({
            name: b.name,
            title: b.title,
            type: 2,
            redirect: b.redirect || '',
          });
        });
        tag.meta.parents = belongList.concat(tag.meta.parents);
      }
    }

    item.children && item.children.map(child => {
      child.meta = {
        ...child.meta,
        module: {
          name: item.name,
          meta: {
            ...item.meta,
            isShow: item.isShow || false,
            type: 1,
          },
          redirect: item.redirect || '',
        },
      };

      addParents(child, item.children, child);

      if (child.belong && child.belong.length) {
        addMenu(child.belong, module.children, item => {
          item.push({
            name: child.name,
            redirect: child.redirect || '',
            meta: {
              ...child.meta,
              type: 3,
              isShow: child.isShow || false,
            }
          });
        });
      } else {
        module.children.push({
          name: child.name,
          redirect: child.redirect || '',
          meta: {
            ...child.meta,
            type: child.isShow ? 3 : 5,
            isShow: child.isShow || false,
          }
        });
      }
    });

    routes.push(item);
    userPermission.push(module);
  });

  intoRecurse(allRouters, item => {
    if (item.affix) {
      affixRouters.push({
        name: item.name,
        params: item.params,
        title: item.meta && item.meta.title,
        moduleName: item.meta.module && item.meta.module.name
      });
    }
  });

  routes.push({ path: '/', redirect: { name: 'Permission' }});
  routes.push({ path: '*', redirect: '/404' });
  store.commit('user/SET_PERMISSION', userPermission);
  store.commit('layout/setAffixTagViews', affixRouters);
}

const createRouter = () => new VueRouter({
    routes
  }),
  [routerPush, routerReplace] = [VueRouter.prototype.push, VueRouter.prototype.replace],
  router = createRouter();

VueRouter.prototype.push = function push(location) { // 解决重复跳转当前路由报错
  return routerPush.call(this, location).catch(error => error);
};
VueRouter.prototype.replace = function replace(location) {
  return routerReplace.call(this, location).catch(error => error);
};

// 重置路由
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}

export default router;
